package com.ilibrary.service.impl;

import java.lang.reflect.InvocationTargetException;

import org.apache.catalina.User;
import org.apache.commons.beanutils.BeanUtils;

import com.ilibrary.base.MyBaseVO;
import com.ilibrary.constants.MyMsgConstants;
import com.ilibrary.db.dao.hibernate.UserInfoDao;
import com.ilibrary.db.entity.UserInfo;
import com.ilibrary.service.UserInfoService;
import com.ilibrary.utils.MD5Utils;
import com.ilibrary.web.dto.ResultDto;
import com.ilibrary.web.vo.UserInfoVO;

public class UserInfoServiceImpl implements UserInfoService {
	
	private UserInfoDao userInfoDao;

	public UserInfoDao getUserInfoDao() {
		return userInfoDao;
	}
	public void setUserInfoDao(UserInfoDao userInfoDao) {
		this.userInfoDao = userInfoDao;
	}
	
	@Override
	public ResultDto<UserInfoVO> findById(String userId) {
		ResultDto<UserInfoVO> resultDto = new ResultDto<UserInfoVO>();
		UserInfoVO userInfoVO = new UserInfoVO();
		UserInfo userInfo = userInfoDao.findById(userId);
		if(userInfo != null) {
			try {
				BeanUtils.copyProperties(userInfoVO, userInfo);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			resultDto.addToResultList(userInfoVO);
			resultDto.setSuccess(true);
		}else {
			resultDto.setSuccess(false);
			resultDto.setMsg(MyMsgConstants.LOGIN_ERROR_INVALID);
		}
		return resultDto;
	}
	
	@Override
	public ResultDto<MyBaseVO> updateUserPassword(String userId,
			String oldPassword, String newPassword) {
		ResultDto<MyBaseVO> resultDto = new ResultDto<MyBaseVO>();
		UserInfo userInfo = userInfoDao.findById(userId);
		if(!MD5Utils.generateForPassword(oldPassword).equals(userInfo.getUserPwd())) {
			resultDto.setSuccess(false);
			resultDto.setMsg(MyMsgConstants.UPDATE_PASSWORD_FAILD_BY_NOT_MATCH);
			return resultDto;
		}
		userInfo.setUserPwd(MD5Utils.generateForPassword(newPassword));
		userInfoDao.update(userInfo);
		resultDto.setSuccess(true);
		return resultDto;
	}
	
	
}
